package cn.wjc.demo.common.aspect;

import cn.wjc.demo.common.annotation.JustAnnotation;
import cn.wjc.demo.common.annotation.TestAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class MyAnnotationAspect {

    @Pointcut("@annotation(cn.wjc.demo.common.annotation.JustAnnotation) ||" +
            "@annotation(cn.wjc.demo.common.annotation.TestAnnotation)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) {
        // 参数值
        Object[] args = pjp.getArgs();
        // 方法
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();

        if (method.isAnnotationPresent(JustAnnotation.class)) {
            Annotation annotation = method.getAnnotation(JustAnnotation.class);
            String str = ((JustAnnotation) annotation).str();
            log.info("{}注解了{}，str={}",method.getName(), annotation.getClass().getName(), str);
        } else if (method.isAnnotationPresent(TestAnnotation.class)) {
            Annotation annotation = method.getAnnotation(TestAnnotation.class);
            String str = ((TestAnnotation) annotation).str();
            log.info("{}注解了{}，str={}",method.getName(), annotation.getClass().getName(), str);
        }

        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return "error";
    }
}
